package com.lin;

import lombok.SneakyThrows;

import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @Author zimingl
 * @Date 2023/4/29 20:12
 * @Description: SynchronizedTest01 读写锁
 */
public class SynchronizedTest01 {
    private static final Object lock = new Object();

    static int count = 0;

    @SneakyThrows
    public static void main(String[] args) {
        write();
        read();
    }

    private static void write() {
        new Thread(() -> {
            synchronized (lock) {
                System.out.println("write start ...");
                count++;
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("write end ...");
            }
        }).start();
    }

    @SneakyThrows
    private static void read() {
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            synchronized (lock) {
                System.out.println("read start ...");
                TimeUnit.MILLISECONDS.sleep(1);
                return count;
            }
        });
        new Thread(futureTask).start();
        Integer integer = futureTask.get();
        System.out.println(integer);
    }
}
